<template>
  <div class="bill-management">
    <!-- 搜索区域 -->
    <el-form :model="searchForm" inline label-width="80px" class="search-form">
      <el-form-item label="账单编号">
        <el-input v-model="searchForm.billNo" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="老人姓名">
        <el-input v-model="searchForm.name" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="老人身份证号">
        <el-input v-model="searchForm.idCard" placeholder="请输入" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 状态切换 + 生成月度账单按钮 -->
    <div class="tab-and-button">
      <el-radio-group v-model="activeTab" @change="handleSearch">
        <el-radio label="all">全部</el-radio>
        <el-radio label="unpaid">待支付</el-radio>
        <el-radio label="paid">已支付</el-radio>
        <el-radio label="closed">已关闭</el-radio>
      </el-radio-group>
      <el-button type="primary" @click="handleGenerateMonthlyBill">生成月度账单</el-button>
    </div>

    <!-- 账单表格（含操作列） -->
    <el-table :data="tableData" border style="width: 100%" :loading="loading">
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="billNo" label="账单编号" />
      <el-table-column prop="billType" label="账单类型" />
      <el-table-column prop="billMonth" label="账单月份" />
      <el-table-column prop="elderlyName" label="老人姓名" />
      <el-table-column prop="elderlyIdCard" label="老人身份证号" />
      <el-table-column prop="billAmount" label="账单金额（元）" width="120" />
      <el-table-column prop="payableAmount" label="应付金额（元）" width="120" />
      <el-table-column prop="payDeadline" label="支付截止时间" />
      <el-table-column prop="transactionStatus" label="交易状态">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.transactionStatus)">
            {{ scope.row.transactionStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <!-- 操作列：支付、取消、查看 -->
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="mini" 
            @click="handlePay(scope.row)" 
            :disabled="scope.row.transactionStatus !== '待支付'"
          >支付</el-button>
          <el-button 
            type="warning" 
            size="mini" 
            @click="handleCancel(scope.row)" 
            :disabled="scope.row.transactionStatus !== '待支付'"
          >取消</el-button>
          <el-button 
            type="primary" 
            size="mini" 
            @click="handleView(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[6, 9, 12]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 生成月度账单弹窗 -->
    <el-dialog 
      title="选择老人生成月度账单" 
      v-model="showElderlyDialog" 
      width="50%"
      :before-close="handleDialogClose"
      :close-on-click-modal="false"
    >
      <!-- 弹窗加载状态：等待所有数据获取完成 -->
      <div v-if="dialogLoading" class="dialog-loading">加载中...</div>
      
      <el-table 
        v-else
        :data="allElderlyList" 
        border 
        style="width: 100%"
        :loading="elderlyLoading"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="name" label="老人姓名" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="mini" 
              @click="createMonthlyBill(scope.row)"
              :disabled="isElderlyHasBill(scope.row.name)"
            >
              生成账单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="showElderlyDialog = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/utils/request';
import { useRouter } from 'vue-router';
const router = useRouter();


// 搜索表单
const searchForm = ref({
  billNo: '',   // 账单编号
  name: '',     // 老人姓名
  idCard: ''    // 身份证号
});

// 状态筛选（all/unpaid/paid/closed）
const activeTab = ref('all');

// 表格数据 & 加载状态（当前分页数据）
const tableData = ref([]);  // 当前页账单数据
const loading = ref(false); // 当前页账单加载状态
const total = ref(0);       // 总数据量
const currentPage = ref(1); // 当前页
const pageSize = ref(3);    // 每页条数

// 老人相关数据
const showElderlyDialog = ref(false); // 弹窗显示状态
const allElderlyList = ref([]);       // 所有老人列表（[{name: '老人1'}]）
const elderlyLoading = ref(false);    // 老人列表加载状态

// 新增：所有已账单老人姓名（完整数据，不分页）
const allBilledElderlyNames = ref([]); // 格式：["张三", "李四"]
const dialogLoading = ref(false);      // 弹窗加载状态（等待老人+账单数据）


/**
 * 获取当前页账单列表（原逻辑不变）
 */
const getBillList = () => {
  loading.value = true;
  request({
    url: '/system/bill/list',
    method: 'get',
    params: {
      billNo: searchForm.value.billNo,
      name: searchForm.value.name,
      idCard: searchForm.value.idCard,
      status: activeTab.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
  }).then(res => {
    if (res.code === 200) {
      tableData.value = res.data.list;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.msg || '获取账单失败');
    }
  }).catch(() => {
    ElMessage.error('获取账单失败，请稍后重试');
  }).finally(() => {
    loading.value = false;
  });
};


/**
 * 新增：获取所有已账单老人的姓名列表（对接后端新接口）
 * 后端返回格式示例：{ code: 200, data: ["张三", "李四", "王五"] }
 */
const getAllBilledElderly = () => {
  return new Promise((resolve, reject) => {
    request({
      url: '/system/bill/allBilledElderly', // 后端新增接口
      method: 'get'
    }).then(res => {
      if (res.code === 200) {
        allBilledElderlyNames.value = res.data; // 存储所有已账单老人姓名
        resolve();
      } else {
        ElMessage.error(res.msg || '获取已账单老人列表失败');
        reject();
      }
    }).catch(() => {
      ElMessage.error('获取已账单老人列表失败，请稍后重试');
      reject();
    });
  });
};


/**
 * 获取所有老人列表（原逻辑不变）
 */
const getAllElderlyList = () => {
  return new Promise((resolve, reject) => {
    elderlyLoading.value = true;
    request({
      url: '/system/bill/elderlyList',
      method: 'get'
    }).then(res => {
      if (res.code === 200) {
        allElderlyList.value = res.data.map(name => ({ name }));
        resolve();
      } else {
        ElMessage.error(res.msg || '获取老人列表失败');
        reject();
      }
    }).catch(() => {
      ElMessage.error('获取老人列表失败，请稍后重试');
      reject();
    }).finally(() => {
      elderlyLoading.value = false;
    });
  });
};


/**
 * 修改：判断老人是否已有账单（基于完整的已账单姓名列表）
 * @param {string} name - 老人姓名
 * @returns {boolean} - 已有账单则禁用按钮
 */
const isElderlyHasBill = (name) => {
  // 遍历完整的已账单姓名列表，而非当前页tableData
  return allBilledElderlyNames.value.includes(name);
};


// 搜索按钮（原逻辑不变）
const handleSearch = () => {
  currentPage.value = 1;
  getBillList();
};

// 重置按钮（原逻辑不变）
const handleReset = () => {
  searchForm.value = { billNo: '', name: '', idCard: '' };
  handleSearch();
};


/**
 * 修改：生成月度账单按钮点击事件（同时获取老人+完整账单数据）
 */
const handleGenerateMonthlyBill = () => {
  dialogLoading.value = true; // 显示弹窗加载中
  // 并行请求：获取所有老人列表 + 所有已账单老人姓名
  Promise.all([getAllElderlyList(), getAllBilledElderly()])
    .then(() => {
      showElderlyDialog.value = true; // 两个接口都成功，显示弹窗
    })
    .catch(() => {
      showElderlyDialog.value = false; // 任一接口失败，不显示弹窗
    })
    .finally(() => {
      dialogLoading.value = false; // 关闭加载状态
    });
};


/**
 * 生成月度账单（原逻辑不变）
 */
const createMonthlyBill = (elderly) => {
  console.log(elderly.name);
  ElMessageBox.confirm(
    `确认要为【${elderly.name}】生成月度账单吗？`,
    '生成确认',
    {
      confirmButtonText: '确认生成',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    request({
      url: '/system/bill/generateMonthly',
      method: 'post',
      params: {
        elderlyName: elderly.name
      }
    }).then(res => {
      if (res.code === 200) {
        ElMessage.success('月度账单生成成功！');
        showElderlyDialog.value = false;
        getBillList(); // 刷新当前页账单
        // 同步更新已账单列表：新增刚生成账单的老人
        allBilledElderlyNames.value.push(elderly.name);
      } else {
        ElMessage.error(res.msg || '生成账单失败');
      }
    }).catch(() => {
      ElMessage.error('生成账单失败，请稍后重试');
    });
  }).catch(() => {
    ElMessage.info('已取消生成');
  });
};


// 关闭弹窗（原逻辑不变）
const handleDialogClose = () => {
  showElderlyDialog.value = false;
};

// 支付、取消、查看、分页等方法（原逻辑不变）
const handlePay = (row) => {
  if (!row || !row.elderlyName || !row.billNo) {
    ElMessage.error('数据异常，无法支付');
    return;
  }

  ElMessageBox.confirm(
    `确认支付【${row.elderlyName}】的账单吗？金额：${row.payableAmount}元`,
    '支付确认',
    {
      confirmButtonText: '确认支付',
      cancelButtonText: '取消',
      type: 'primary'
    }
  ).then(() => {
    request({
      url: '/system/bill/pay',
      method: 'put',
      params: { billNo: row.billNo }
    }).then(res => {
      if (res.code === 200) {
        ElMessage.success('支付成功！');
        getBillList();
      } else {
        ElMessage.error(res.msg || '支付失败');
      }
    }).catch(() => {
      ElMessage.error('支付失败，请稍后重试');
    });
  }).catch(() => {
    ElMessage.info('已取消支付');
  });
};

const handleCancel = (row) => {
  if (!row || !row.elderlyName) {
    ElMessage.error('数据异常，无法取消');
    return;
  }

  ElMessageBox.confirm(
    `确认取消【${row.elderlyName}】的账单吗？`,
    '取消确认',
    {
      confirmButtonText: '确认取消',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    request({
      url: '/system/bill/cancel',
      method: 'put',
      params: { billNo: row.billNo }
    }).then(res => {
      if (res.code === 200) {
        ElMessage.success('取消成功！');
        getBillList();
        // 同步更新已账单列表：移除已取消账单的老人
        allBilledElderlyNames.value = allBilledElderlyNames.value.filter(name => name !== row.elderlyName);
      } else {
        ElMessage.error(res.msg || '取消失败');
      }
    }).catch(() => {
      ElMessage.error('取消失败，请稍后重试');
    });
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};

const handleView = (row) => {
  router.push({
    path: '/caiwu/zhangdan/detail',
    query: { billNo: row.billNo }
  });
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  getBillList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getBillList();
};

const getStatusTagType = (status) => {
  switch (status) {
    case '已支付': return 'success';
    case '待支付': return 'warning';
    case '已关闭': return 'info';
    default: return '';
  }
};

// 初始化加载数据
onMounted(() => {
  getBillList();
});
</script>

<style scoped>
.bill-management {
  padding: 20px;
}

.search-form {
  margin-bottom: 16px;
}

.tab-and-button {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.pagination {
  margin-top: 16px;
  text-align: right;
}

.el-radio-group {
  display: flex;
  gap: 20px;
}

.el-table .el-button--mini {
  margin-right: 5px;
}

/* 弹窗加载样式 */
.dialog-loading {
  text-align: center;
  padding: 50px;
  font-size: 16px;
  color: #666;
}
</style>